//
//  ZZPayHandler.m
//  ExpertApp
//
//  Created by zhangxy on 2017/9/13.
//  Copyright © 2017年 sjhz. All rights reserved.
//

#import "ZZPayHandler.h"
#import "WXApi.h"

//#import <AlipaySDK/AlipaySDK.h>

@implementation ZZPayHandler

+(void) startJumppay:(ZZPayType) payType order:(NSDictionary *)params result:(void(^)(int code,NSDictionary *msg)) payResult{
    
    
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].delegate.window animated:YES];
    NSString *apiURL = API_CreateOrderWx;
//     if(payType == ZZPayTypeZFB){
//        apiURL = korder_pay_zfb;
//    }
    
    [NetworkUtil POST:apiURL parameters:params success:^(id responseObject, NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:YES];
        if(payType == ZZPayTypeWX){
                [self jumpToWXBizPay:dictionary result:payResult];
            }else{
                [self jumpToAliPay:dictionary result:payResult];
            }
        
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:YES];
        [PopUtil showMessage:message];
        if(payResult){
            payResult(1,@{@"code":@"1",@"message":@"请求支付信息失败!"});
        }
    }];
}

+(void) startVipPay:(ZZPayType) payType order:(NSString *)orderId result:(void(^)(int code,NSDictionary *msg)) payResult{
    
    
    
//    MBProgressHUD *mb = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].delegate.window];
//    [mb show:YES];
//    NSString *apiURL = kUserInfoOpenVip;
//    if(payType == ZZPayTypeZFB){
//        apiURL = kUserInfoOpenVipzfb;
//    }
//    [NetworkUtil GET:apiURL parameters:@{@"vip_id":orderId} success:^(id responseObject) {
//        [mb hide:YES];
//        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        if ([dictionary[@"code"] integerValue] == kNetworkSuccessCode) {
//            if(payType == ZZPayTypeWX){
//                [self jumpToWXBizPay:dictionary result:payResult];
//            }else{
//                [self jumpToAliPay:dictionary result:payResult];
//            }
//        }
//        else{
//            [PopUtil showMessage:dictionary[@"message"] positionType:PopPositionTypeMiddle];
//        }
//        
//    } failure:^(NSError *error) {
//        [mb hide:YES];
//        if(payResult){
//            payResult(1,@"请求支付信息失败!");
//        }
//    }];
}


+ (void)jumpToWXBizPay:(NSDictionary *) resultDict result:(void (^)(int code, NSDictionary *msg))payResult{
        NSDictionary *dict = [resultDict objectForKey:@"data"];
        if (dict){
            NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
            
//            {
//                "status": 1,
//                "msg": "success",
//                "data": {
//                    "order_no": "wx20180817122732338116",
//                    "sign": "ECC9734264CE5B9CA6196A126225CDCA",
//                    "prepay_id": "wx171228284928906f9d5318b11570523850",
//                    "nonce_str": "aChjhRn85y5BijIw",
//                    "timestamp": 1534480052
//                }
//            }
            
//
                    //调起微信支付
                    PayReq* req             = [[PayReq alloc] init];
                    req.partnerId           = @"1510327101";
                    req.prepayId            = [dict objectForKey:@"prepay_id"];
                    req.nonceStr            = [dict objectForKey:@"nonce_str"];
                    req.timeStamp           = stamp.intValue;
                    req.package             = @"Sign=WXPay";
            req.sign                = [ZZPayHandler getSignParamByDict:req];// [dict objectForKey:@"sign"];
                    BOOL isOK = [WXApi sendReq:req];
            
            if(payResult){
                payResult(0,@{@"code":@"0",@"message":@"",@"order_no":convertToString(dict[@"order_no"])});
            }
            
                    //日志输出
//            NSLog(@"支付接口调用结果：---- %d\n%d\n%@",isOK , stamp.intValue,req.openID);
        }else{
            if(payResult){
                payResult(2,@{@"code":@"2",@"message":@"服务器返回错误，未获取到支付对象"});
            }
        }
}


+(NSArray *) dictSortByKey:(NSDictionary *) dict{
    NSArray *keys = [dict allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    return sortedArray;
}

+(NSString *) getSignParamByDict:(PayReq* )req{
    
//    NSArray *sortedArray = [ZZPayHandler dictSortByKey:dict];
    
    NSString *sign = [NSString stringWithFormat:@"appid=wxe82fac2b2cb433e7&noncestr=%@&package=%@&partnerid=%@&prepayid=%@&timestamp=%d&",req.nonceStr,req.package,req.partnerId,req.prepayId,req.timeStamp];
//
//    for (NSString *key in sortedArray) {
//        sign = [sign stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,dict[key]]];
//    }
    sign = [sign stringByAppendingFormat:@"key=%@",@"8988001f4664042497389c6d147ad023"];
    NSLog(@"排序自动：%@",sign);
    //    [ZCLogUtils logHeader:LogHeader debug:@"sign:%@",sign];
    return [md5(sign) uppercaseString];
}


+(void)jumpToAliPay:(NSDictionary *) dict result:(void (^)(int code, NSDictionary *msg))payResult{
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = dict[@"data"];
    if (orderString != nil) {
//        NSString *signedString = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";
//        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
//                       orderString, signedString, @"RSA"];
        
//        [[AlipaySDK defaultService] payOrder:orderString fromScheme:@"deerkids" callback:^(NSDictionary *resultDic) {
//            NSLog(@"reslut = %@",resultDic);
//
//
//        }];
    }
}

@end
